<?php

namespace app\admin\model;

use think\Model;


class Userrelation extends Model
{

    

    

    // 表名
    protected $name = 'user_relation';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];



    public function addUserRelation($newUid, $uid)
    {

        $userRelation = $this->where('uid', $uid)->find();
        if ($userRelation) {

            //1.添加上级关系链
            $relationship = $uid . "," . $userRelation['relation'];
            $data = array();
            $data['uid'] = $newUid;
            $data['relation'] = $relationship;
            $data['refUid'] = $uid;
            $this->insert($data);
            //2.团队人数+1
            $teams = explode(",", $relationship);
            $ids = [];
            foreach ($teams as $val) {
                $ids[] = $val;
            }
            $where = ['uid' => ['in', $ids]];
            $userRelation->where($where)->setInc('d_count', 1);
            $userRelation->where($where)->setInc('t_count', 1);

        } else {
            $data = array();
            $data['uid'] = $newUid;
            $data['relation'] = "1";
            $data['refUid'] = 1;

            $this->insert($data);
        }
    }






}
